package com.ming.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.yygh.cmn.listener.DictListener;
import com.ming.yygh.cmn.mapper.DictMapper;
import com.ming.yygh.cmn.service.DictService;
import com.ming.yygh.model.cmn.Dict;
import com.ming.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Light
 * @date 2021/11/15 15:16
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    // 根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(String id) {
        List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", id));
        // 向list集合每个对象中设置hasChildren
        dictList.forEach(dict -> {
            String dictId = dict.getId();
            Boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        });
        return dictList;
    }

    // 导出数据字典
    @Override
    public void exportDictData(HttpServletResponse response) {
        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 这和easyexcel没关系
        String fileName = URLEncoder.encode("数据字典", StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        // Dict =>(转化为) DictEeVo
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        dictList.forEach(dictData -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dictData, dictEeVo);
            dictEeVoList.add(dictEeVo);
        });

        // 调用easyExcel方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 导入数据字典
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Dict getDictName(String dictCode, String value) {
        // 如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            // 直接根据value查询
            return baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
        } else { // 如果dictCode不为空，直接根据dictCode和value查询
            // 先根据dictCode查询dict对象，得到dict的id值
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
            String dictId = dict.getId();
            // 根据parentId和value进行查询
            return baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", dictId)
                    .eq("value", value));
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据dictCode获取对应的id
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        // 根据id获取子节点
        return this.findChildData(dict.getId());
    }

    // 判断id下面是否有子节点
    private Boolean isChildren(String id) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        return count > 0;
    }
}
